<template>
    <div>
        		<!-- 创建Checker脚本 -->
		<Modal  v-model="checkerModal" :title="modelTitle" width="600" :mask-closable="false" :footer-hide="true" @on-visible-change='watchStatus'>
			<Form ref="scriptForm" :model="scriptForm" :rules="scriptRule" :label-width="80">
				<FormItem label="名称" prop="name">
                    <i-input v-model.trim="scriptForm.name" placeholder="名称"></i-input>
                </FormItem>
				<FormItem label="可见范围" prop="visibility">
                    <RadioGroup v-model="scriptForm.visibility">
                        <Radio label="share">单位</Radio>
                        <Radio label="private">个人</Radio>
                    </RadioGroup>
                </FormItem>
				<FormItem label="语言" prop="language">
                    <Select filterable v-model="scriptForm.language" placeholder="青选择语言">
                        <Option value="python">python</Option>
                        <Option value="java">java</Option>
                        <Option value="shell">shell</Option>
                    </Select>
                </FormItem>
				<FormItem label="协议类型" prop="protocol">
                    <RadioGroup v-model="scriptForm.protocol">
                        <Radio label="tcp">tcp</Radio>
                        <Radio label="udp">udp</Radio>
                    </RadioGroup>
                </FormItem>
				<FormItem label="端口" prop="serverPort">
                    <i-input v-model="scriptForm.serverPort" placeholder="请输入1~65535的整数"></i-input>
                </FormItem>
				<FormItem label="操作系统" prop="sysType">
                    <CheckboxGroup v-model="scriptForm.sysType">
                      <Checkbox label="windows">Windows</Checkbox>
                      <Checkbox label="linux">Linux</Checkbox>
                      <Checkbox label="unix">Unix</Checkbox>
                      <Checkbox label="macos">macOS</Checkbox>
                    </CheckboxGroup>  
                </FormItem>
				<FormItem label="命令" prop="cmd">
                    <i-input v-model.trim="scriptForm.cmd" placeholder="命令"></i-input>
                </FormItem>
				<FormItem  label="文件" prop="path" key="path">
	               <section>
	                 <Row>
	                   <!--<Col span="5" >-->
	                     <Upload ref="upload"
	                             v-model="scriptForm.path"
                                :action="checkerUpdateUrl"
                                :show-upload-list="false"
								:format="['sh','py']"
                                :on-format-error="checkerHandleFormatError"
                                :on-success="checkerGetImageUrl"
                                :before-upload="checkerHandleUpload"
								style="display: inline-block;">
	                       <Button icon="ios-cloud-upload-outline" :disabled="!showName">请选择要上传的文件</Button>
	                       <span v-if="showName">{{checkerFilename}}</span>
	                     </Upload>
						 <WarningTip content="请上传sh，py格式文件"></WarningTip>
                         <div style="margin-top:10px;" v-if='scriptForm.path != "" && scriptForm.path != null'>
                            文件路径：{{scriptForm.path}}<br>
                            <p style="color:red;font-size:12px;">(备注:可将文件路径复制到命令或者参数内,可用作命令或参数)</p>
                         </div>   
	                 </Row>
	                 <!-- <p v-if="showTip" style="color:red;">请上传文件</p> -->
	                 <!-- <div class="ivu-form-item-error-tip" v-if="uploaderror">{{$t('updateFile')}}</div> -->
	               </section>
	            </FormItem>
				<FormItem
                        v-for="(item, index) in scriptForm.args"
                        :key="index"
                        :label="Args+''+(index+1)">
                    <Row>
                        <i-Col span="19">
                            <i-input type="text" v-model="scriptForm.args[index]" placeholder="arg" @click.native="getFocus(index)"  @input="getValue(scriptForm.args[index],index)"></i-input>
                        </i-Col>
                        <i-Col span="3" offset="1">
                            <Button type='error' @click="handleRemove(index)">删除</Button>
                        </i-Col>
                    </Row>
                </FormItem>
				<FormItem>
                    <Row>
                        <i-Col span="12">
                            <Button type="dashed" long @click="handleAdd" class="md-add-jh">添加</Button>
                        </i-Col>
                    </Row>
                </FormItem>
				<FormItem label="成功标识" prop="conditionForSuccess">
                    <i-input v-model="scriptForm.conditionForSuccess" placeholder="脚本输出成功后包含的字符串"></i-input>
                </FormItem>
				<FormItem label="执行示例">
                    <Row>
                        <i-Col span="24">
                            <pre class="pre-Info">{{scriptForm.cmd+'&nbsp;'}}{{checkerFilename+'&nbsp;'}}<code v-for="(item,index) in showArr" :key="index">{{showArr[index]}}&nbsp;</code></pre>
                        </i-Col>
                    </Row>
                </FormItem>
				<FormItem label="描述" prop="description">
                    <i-input v-model.trim="scriptForm.description" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="描述"></i-input>
                </FormItem>
				<FormItem>
                    <Button type="primary" @click="subScriptBtn('scriptForm')" :loading="subLoading">确定</Button>
                    <Button v-show="scriptId? false : true" @click="resetBtn('scriptForm')" style="margin-left: 8px">重置</Button>
                    <Poptip v-show="scriptId? true : false" transfer confirm title="确定要删除这个脚本？" placement="right" @on-ok="deleteDoc()">
						<Button type='error' style="margin-left: 8px">删除脚本</Button>
					</Poptip>
                </FormItem>
			</Form>
			<div v-if="showdic" class="dictionaries">
                <div style="display: flex;justify-content: flex-end;margin-bottom: 10px;">
                    <div @click="closedic" style="cursor: pointer;"> 
                        <Icon type="md-close" />
                    </div>
                </div>
                <Table :columns="argsDicCol" :data="dicList"></Table>
            </div>
		</Modal>


		<!-- 镜像部分 -->
		<!-- 创建镜像 -->
		<Modal 
			v-model="imageModal"
			:mask-closable="false"
			width="800"
			:footer-hide="true"
			@on-visible-change="watchModalStatus" 
			title="镜像">
			<Form ref="imageFormData" :model="imageFormData" :rules="creatImageRuleValidate" :label-width="120" style="width: 500px">
				<FormItem label="虚拟化类型" prop="virtualization">
					<RadioGroup v-model="imageFormData.virtualization">
						<Radio label="kvm">kvm</Radio>
						<Radio label="docker">docker</Radio>
					</RadioGroup>
				</FormItem>
				<FormItem label="名称" prop="imageName">
					<Input v-model.trim="imageFormData.imageName" placeholder="名称"></Input>
					<p style="color:#f90" v-if="imageFormData.virtualization == 'docker'"><Icon type="ios-information-circle-outline" />docker类型镜像,镜像名称和源镜像名称需要保持一致,否则会导致镜像无法正常使用</p>
				</FormItem>
				<FormItem label="硬盘最小值(GB)" prop="minDisk">
					<InputNumber :max="1024"  :step="1" v-model="imageFormData.minDisk" style="width: 130px"></InputNumber>
				</FormItem>
				<FormItem label="内存最小值(MB)" prop="minRam">
					<InputNumber :max="65536" :step="1" v-model="imageFormData.minRam" style="width: 130px"></InputNumber>
				</FormItem>
				<FormItem label="Profile" prop="profileId">
					<div style="display: flex;justify-content: flex-start;width: 580px;">
						<Select filterable v-model="imageFormData.profileId" placeholder="请选择profile" style="width: 380px;" @on-change="getProfileName">
							<Option :value="value.id" v-for="(value,index) in profileList" :key="index"  :title="value.osName">{{value.osName}}</Option>
						</Select>
						<Tooltip style="margin-left: 10px;" :transfer='true' max-width="200" content="带外采集专用参数，制作镜像时没有配置此项，上传的镜像不支持带外采集无需配置" placement="top">
							<Icon type="ios-alert" class="ios-alert" />
						</Tooltip>
					</div>
				</FormItem>
				<FormItem label="系统类型" prop="osType">
					<Select filterable v-model="imageFormData.osType" placeholder="选择系统类型">
						<Option value="linux">Linux</Option>
						<Option value="windows2003">Windows2003</Option>
						<Option value="unix">Unix</Option>
						<Option value="windows7">Windows7</Option>
						<Option value="windowsXP">WindowsXP</Option>
						<Option value="windows">Windows</Option>
					</Select>
				</FormItem>
				<FormItem label="可见范围" prop="visibility">
					<RadioGroup v-model="imageFormData.visibility">
						<Radio label="share">单位</Radio>
						<Radio label="private">个人</Radio>
					</RadioGroup>
				</FormItem>
				<FormItem label="设备类型" prop="nodeType">
					<Select filterable v-model="imageFormData.nodeType" placeholder="选择设备类型">
						<Option value="vm">VM</Option>
						<Option value="firewall">firewall</Option>
						<Option value="ids">IDS</Option>
						<Option value="waf">WAF</Option>
						<Option value="drout">Drout</Option>
						<Option value="des">DES:离散事件仿真节点</Option>
						<Option value="base">BASE</Option>
					</Select>
				</FormItem>
				<FormItem label="HasQga" prop="hasQga">
					<i-switch v-model="imageFormData.hasQga" size="large">
						<span slot="open">true</span>
						<span slot="close">false</span>
					</i-switch>
				</FormItem>
				<FormItem label="HasVirtoDriver" prop="hasVirtoDriver">
					<i-switch v-model="imageFormData.hasVirtoDriver" size="large">
						<span slot="open">true</span>
						<span slot="close">false</span>
					</i-switch>
				</FormItem>
				<FormItem label="HasHtPlug" prop="htPlug">
					<i-switch v-model="imageFormData.htPlug" size="large">
						<span slot="open">true</span>
						<span slot="close">false</span>
					</i-switch>
				</FormItem>
				<FormItem label="HasCloudInit" prop="hasCloudInit">
					<i-switch v-model="imageFormData.hasCloudInit" size="large">
						<span slot="open">true</span>
						<span slot="close">false</span>
					</i-switch>
				</FormItem>
				<FormItem  label="上传文件"  prop="file">
                    <Upload
                            v-model="imageFormData.file"
                            :action="updateUrl"
                            :before-upload="handleUpload">
                        <Button icon="ios-cloud-upload-outline" :disabled="setDisabled">选择文件</Button>
                    </Upload>
                    <Tooltip placement="right-start"  content='请上传qcow2、docker类型的镜像' class="too">
                        <Icon type='ios-help-circle' style="cursor: pointer;" color='rgb(203, 2, 54)'></Icon>    
                    </Tooltip>
                    <div v-if="progressflag">
                        <p>文件名: {{ fileName }}</p>
                        <p>size:<span v-text="imageFileSize"></span></p>
                        <Progress :percent="progress"></Progress>
                        <p>speedd:<span v-text="speedd"></span></p>
                    </div>
                </FormItem>
				<FormItem label="描述" prop="description">
                    <Input v-model.trim="imageFormData.description" type="textarea"
                           :autosize="{minRows: 2,maxRows: 5}" placeholder="描述" :maxlength="200"></Input>
                </FormItem>
				<FormItem>
                    <Button type="primary" @click="submitBtn('imageFormData')" :loading="addImageBtnLoading" :disabled="setDisabled">确定</Button>
                    <Button @click="creatImageHandleReset('imageFormData')" style="margin-left: 8px">重置</Button>
                </FormItem>
			</Form>
		</Modal>
    </div>
</template>

<script>
	import {getDictionaries, addScripts, delScripts, queryCheck,bindingCheck,modifyScript,unboundCheck,bindingSub,unboundSub} from '@/api/target.js' 
import { getProfile, mergeFiles } from '@/api/image.js'
	import { validateNameCustom,newValidationRules} from '@/libs/reg.js'
const portValidator = (rule, value, callback) => {
	if (value) {
		let reg = /^[0-9]*$/
		if (!(parseInt(value) > 0 && parseInt(value) <= 65535)) {
			callback(new Error('请输入1-65535之间的数字'));
		} else if (!reg.test(value)) {
			callback(new Error('请输入整数'));
		} else {
			callback();
		}
	} else {
		callback();
	}
};
	const listData = {
					"args": [''],
					"cmd": "",
					"conditionForSuccess": "",
					"description": "",
					//   "imageId": "",
					"language": "python",
					"name": "",
					"path": "",
					"protocol": "tcp",
					"serverPort": 1,
					"sysType": [],
					"visibility": "share"
					};
	const validateMinram = (rule,value,callback) => {
    	let reg=/^\d+$/;
    	if(reg.test(value)){
		    let val = parseInt(value)
		    if(val >= 128 && val <= 65536){
			    return callback()
		    }else {
			    return callback(new Error('内存大小为128MB到65536MB之间'))
		    }
        }else{
		    return callback(new Error('请输入整数'))
        }

    }

	const validateMindisk = (rule,value,callback) => {
	    let reg=/^\d+$/;
	    if(reg.test(value)){
		    let val = parseInt(value)
		    if(val >= 1 && val <= 1024){
			    return callback()
		    }else {
			    return callback(new Error('硬盘大小为1GB到1024GB之间'))
		    }
        }else{
		    return callback(new Error('请输入整数'))
        }

}
		 const validateName = (rule, value, callback) => {
      //验证警戒值
      if (value) {
        validateNameCustom(rule, value, callback, 128)
      } else {
        callback()
      }
    }
    export default {
        name:'checker',
        props:[],
        data () {
            return {
                // checker部分
                checkerUpdateUrl:'/api/checker/scripts/upload',
				checkerModal:false,
				scriptForm:listData,
				checkerShowTip:false,
				checkerFilename:'',
				showName:true,
				showArr:[''],
				Args:'参数',
				showdic:false,
				nums:0,
				dicList:[],
				subLoading:false,
				modelTitle:'',// model标题
				SubTarId:'', //靶标id
				scriptId:'', //脚本id
				tarSetInterval:'', // 定时器
				subFlag:false,
				scriptRule:{
					name: [
						{ required: true, message: '名字不能为空', trigger: 'change' },
						{ type: 'string', max: 100, message: '长度不能超过100位', trigger: 'change' }
					],
					protocol: [
						{ required: true, message: '请选择协议类型', trigger: 'change' }
					],
					// protocol: [
					// 	{ required: true, message: this.$t('selectProtocolType'), trigger: 'change' }
					// ],
					serverPort: [
						{ validator: portValidator,trigger: 'change' }
					],
					cmd: [
						{ required: true,message: '命令不能为空', trigger: 'change' }
					],
					conditionForSuccess: [
						{ required: true,message: '成功标识不能为空', trigger: 'change' }
					],
					sysType: [
						{ required: true, message: '请选择操作系统'}
					],
					visibility : [
						{ required: true, message: '请选择可见范围', trigger: 'change' }
					],
					path:[{ required: true,message: '请上传文件' }],
					description: [
						{ max: 150, message:'最大长度为150', trigger: 'change' }
					]
				},
				argsDicCol:[
					{
						title:'参数',
						key:'key',
						align:'center',
						fixed: 'left',
						render:(h,params)=>{
							return h('Button',{
								props:{
									type:'info',
									size:'small',
								},
								style:{
									'font-size':'12px'
								},
								on:{
									click:()=>{
										this.setArrs(params.row.key)
									}
								}
							},params.row.key)
						}
					},
					{
						title:'含义',
						key:'value',
						align:'center'
					},
					{
						title:'示例',
						key:'example',
						align:'center'
					},
				],

				
				//镜像部分
				imageModal:false,
				flag:0, //标记成功的次数
				filedArr:[],//承装切片的容器
				progressflag:false,//控制进度条的展示
				progress:0, //控制进度条
				//profile
                profileList:[],
				updateUrl:`/api/resource-manager/image/add`,
				
				speedd: 0,
				setDisabled:false,
				fileName:'',
				imageFileSize:0,
				addImageBtnLoading:false,
				imageFormData:{
                    imageName:'',
                    minDisk:0,
                    minRam:0,
                    profileId:'',
                    profileName:'',
                    osType:'',
                    virtualization:'kvm',
                    visibility:'share',
                    nodeType:'VM',
                    hasQga:false,
                    hasVirtoDriver:false,
                    htPlug:false,
                    hasCloudInit:false,
                    description:'',
                    file:null,
                    hwVifModel:'',
                    hwDiskBus:'',
                    tempId:''
                },
				creatImageRuleValidate:{
                    imageName: [
                        { required: true, message: '名称不能为空', trigger: 'change' },
						{ max: 128, message: '名称长度不能超过128个字符', trigger: 'change' },
												 { validator: validateName, trigger: 'change' }
                    ],
                    virtualization: [
                        { required: true, message: '虚拟化类型不能为空', trigger: 'change' }
                    ],
                    visibility: [
                        { required: true, message: '可见范围不能为空', trigger: 'change' }
                    ],
                    osType:[
                        { required: true, message: '系统类型不能为空', trigger: 'change' }
                    ],
                    minRam:[
                        { required: true, validator: validateMinram, trigger: 'change' },
                    ],
                    minDisk:[
                        { required: true, validator: validateMindisk, trigger: 'change' },
                    ],
                    description:[
                        { max: 200, message: '描述长度不能超过200个字符', trigger: 'change' },
                    ],
                },
            }
        },
        methods:{
            //checker部分
			checkerHandleFormatError(){
				this.checkerShowTip = true;
				this.$Message.error({content:'请上传sh，py格式文件',duration:5, closable: true})
				this.checkerFilename = '';
			},
			checkerHandleUpload(file){
				const name = file.name
				this.checkerFilename = name
			},
			checkerGetImageUrl(res){
				this.showName = true;
				if(res.code==1){
					this.scriptForm.path = res.data;
					this.$refs.scriptForm.validateFields('path')
				}else{
					this.$Message.warning({content: '操作失败', duration: 3});
				}
			},
			handleAdd(){
				this.scriptForm.args.push('');
			},
			getFocus(index){
				this.nums = index;
				this.showdic = true;
			},
			getValue(val,index){
				this.showArr[index] = val;
				for(let i = 0;i<this.dicList.length;i++){
					let k = this.dicList[i].key;
					let v = this.dicList[i].example;
					this.showArr[index] = this.showArr[index].replace(new RegExp(k,"gm"),v);
				}
			},
			handleRemove(index){ //删除参数
				if(this.scriptForm.args.length<=1){
					return this.$Message.info({content:'请最少保留一条参数',duration:3})
				}
				this.scriptForm.args.splice(index,1)
        		this.showArr.splice(index,1)
			},
			closedic(){
				this.showdic = false;
			},
			queryDictionaries(){//查询字典 获取焦点展示的内容
				getDictionaries().then(res => {
					if (res.code === 1) {
					this.dicList = res.data;
					}else{
					this.$Message.warning(res.message);
					}
				}).catch(err => {
					//
				})},
			setArrs(arr){
				this.$set(this.scriptForm.args, this.nums, this.scriptForm.args[this.nums]+""+arr)
				this.showArr[this.nums] = this.scriptForm.args[this.nums];
				for(let i in this.dicList){
					let k = this.dicList[i].key;
					let v = this.dicList[i].example;
					this.showArr[this.nums] = this.showArr[this.nums].replace(new RegExp(k,"gm"),v);
				}
			},
			subScriptBtn(name){
				if(!this.scriptId){
					this.saveScript(name)
				}else{
					//修改脚本
					this.modifySubmit(name)
				}
				
			},
			resetBtn(name){
				this.checkerFilename = '';
				this.scriptForm = Object.assign({}, listData);
				this.scriptForm.args = [''];
				this.showArr = [];
				this.$refs[name].resetFields();
			},
			saveScript(name){
				this.$refs[name].validate((valid) => {
					if (valid) {
						let types = '';
						// console.log(this.scriptForm.sysType);
						// for(let i in this.scriptForm.sysType){
						// 	types += this.scriptForm.sysType[i]+','
						// }
						// types = types.substring(0,types.length-1);
						types = this.scriptForm.sysType.join(',')
						let params = {
							"args": this.scriptForm.args,
							"cmd": this.scriptForm.cmd,
							"conditionForSuccess": this.scriptForm.conditionForSuccess,
							"description": this.scriptForm.description,
							"imageId": this.scriptForm.imageId,
							"language": this.scriptForm.language,
							"name": this.scriptForm.name,
							"path": this.scriptForm.path,
							"protocol": this.scriptForm.protocol,
							"serverPort": this.scriptForm.serverPort,
							"sysType": types,
							"visibility": this.scriptForm.visibility,
						}
						// let arr = []
						// for(let i=0;i<this.scriptForm.args.length;i++){
						//     if(this.scriptForm.args[i].key === '' || this.scriptForm.args[i].value === ''){
						//         arr.push('1')
						//     }
						// }
						// if(arr.length > 0){
						//     this.$Message.error({content:'参数的kv不能为空',duration:3})
						//     return false
						// }
						this.subLoading = true
						addScripts(params).then(res=>{
								if(res.code === 1){
									this.checkerModal = false
									let Script = res.data.id
									if(this.subFlag){
										bindingSub(this.SubTarId,Script).then(res=>{
											if(res.code===1){
												this.$Message.success({content:'脚本创建成功！',duration:3})
												this.$emit('queryCtfList')
											}else{
												this.$Message.success({content:'脚本创建成功，绑定靶标失败！',duration:3})
											}											
										})
									}else{
										bindingCheck(this.SubTarId,Script).then(res=>{
											if(res.code===1){
												this.$Message.success({content:'脚本创建成功！',duration:3})
												this.$emit('queryTargetList')
											}else{
												this.$Message.success({content:'脚本创建成功，绑定靶标失败！',duration:3})
											}
										})
									}
								}else{
									this.$Message.error({content:res.message,duration:3})
								}
								this.subLoading = false
						}).catch(err=>{
							this.subLoading = false
							this.$Message.warning(res.message);
						})
					} else {
						this.$Message.error({content:'请完善信息！',duration:3,});
					}
				})
			},
			deleteDoc(){
				if(this.subFlag){
					unboundSub(this.scriptId).then(res=>{
						if(res.code==1){
							delScripts(this.scriptId).then(res=>{
								if(res.code==1){
									this.$Message.success({content:'删除checker脚本成功！',duration:3,});
									this.$emit('queryCtfList')
									this.checkerModal = false
								}else{
									this.$Message.error({content:'删除checker脚本成功！',duration:3,});
								}
							})
						}else{
							this.$Message.warning(res.message);
						}
					}).catch(err=>{
						
					})
				}else{
					unboundCheck(this.scriptId).then(res=>{
						if(res.code==1){
							delScripts(this.scriptId).then(res=>{
								if(res.code==1){
									this.$Message.success({content:'删除checker脚本成功！',duration:3,});
									this.$emit('queryTargetList')
									this.checkerModal = false
								}else{
									this.$Message.error({content:'删除checker脚本成功！',duration:3,});
								}
							})
						}else{
							this.$Message.warning(res.message);
						}
					}).catch(err=>{
						
					})
				}

			},
			//点击脚本的回调
			openCheck(item){
				this.subFlag = item.subFlag //标记主观题
				this.showdic = false; // 关闭字典框
				this.SubTarId = item.id //存储靶标或者主观题的id进行绑定操作
				let subTarId = item.scriptId || item.verifyScriptId
				if(subTarId){
					//查询脚本详细信息
					queryCheck(subTarId).then(res=>{
						if(res.code==1){
						let params = res.data.items[0]
							this.modifyScript(params)
						}else{
							this.$Message.warning(res.message);
						}
					}).catch(err=>{
						this.$Message.warning({content:'连接失败，请检查网络设置!',duration:3,});
					})
				}else{
					this.addChecker(item)
				}
				
			},
			addChecker(item){
				this.modelTitle = '添加脚本'
				this.scriptId = ''
				this.scriptForm = Object.assign({}, listData);
				this.checkerModal = true;
				this.checkerFilename = '';
				this.scriptForm.args = [''];
				this.showArr = [];
			},
			//修改脚本
			modifyScript(params){
				this.scriptId = params.id
				this.modelTitle = '修改脚本'
				let sysType = [];
				if(params.sysType != ''){
					sysType = params.sysType.split(',');
				}
				this.showArr = JSON.parse(params.argArr);
				for(let i = 0;i<this.showArr.length;i++){
					for(let j = 0;j<this.dicList.length;j++){
						let k = this.dicList[j].key;
						let v = this.dicList[j].example;
						this.showArr[i] = this.showArr[i].replace(new RegExp(k,"gm"),v);
					}
				}
				if(JSON.parse(JSON.stringify(params)).path != null){
					let len = JSON.parse(JSON.stringify(params)).path.length;
					if(len > 0 && params.path != ''){
						this.filename =  params.path.substring(params.path.toString().indexOf("_")+1,len);
					}else{
						this.filename = '';
					}
				}
				this.scriptForm = {
					"args": params.argArr?JSON.parse(params.argArr):[''],
					"cmd": params.cmd?params.cmd:'',
					"conditionForSuccess": params.conditionForSuccess?params.conditionForSuccess:'',
					"description": params.description?params.description:'',
					"imageId": params.imageId?params.imageId:'',
					"language": params.language?params.language:'',
					"name": params.name?params.name:'',
					"path": params.path?params.path:'',
					"protocol": params.protocol?params.protocol:'',
					"serverPort": params.serverPort?params.serverPort:'',
					"sysType": sysType,
					"visibility": params.visibility?params.visibility:'',
				}
				this.checkerModal = true
			},
			modifySubmit(name){
				this.$refs[name].validate((valid) => {
					if (valid) {
						let types = '';
						// for(let i in this.scriptForm.sysType){
						// 	types += this.scriptForm.sysType[i]+','
						// }
						// types = types.substring(0,types.length-1);
						types = this.scriptForm.sysType.join(',')
						let params = {
							"args": this.scriptForm.args,
							"cmd": this.scriptForm.cmd,
							"conditionForSuccess": this.scriptForm.conditionForSuccess,
							"description": this.scriptForm.description,
							"imageId": this.scriptForm.imageId,
							"language": this.scriptForm.language,
							"name": this.scriptForm.name,
							"path": this.scriptForm.path,
							"protocol": this.scriptForm.protocol,
							"serverPort": this.scriptForm.serverPort,
							"sysType": types,
							"visibility": this.scriptForm.visibility,
						}
						// let arr = []
						// for(let i=0;i<this.scriptForm.items.length;i++){
						//     if(this.scriptForm.items[i].key === '' || this.scriptForm.items[i].value === ''){
						//         arr.push('1')
						//     }
						// }
						// if(arr.length > 0){
						//     this.$Message.error({content:'参数的kv不能为空',duration:3})
						//     return false
						// }
						this.subLoading = true
						modifyScript(this.scriptId,params)
							.then(res=>{
								if(res.code === 1){
									this.$Message.success({content:res.message,duration:3})
									this.checkerModal = false
								}else{
									this.$Message.error({content:res.message,duration:3})
								}
								this.subLoading = false
							})
							.catch(err=>{
								this.subLoading = false
							})
					} else {
						this.$Message.error({content:'请完善信息！',duration:3,});
					}
				})
			},


			//镜像部分
			addImage(){
				this.imageModal = true
				this.getProfileData()
				this.speedd = 0
				this.imageFileSize = 0
				if(!this.filedArr.length){
                    this.flag = 0 //清空标志位,防止进度条错乱
                    this.progress=0 // 重置进度条
                }
			},
			// 监控modal状态
            watchModalStatus(val){
                if(!val){
                    this.creatImageHandleReset('imageFormData')
                }
            },

			creatImageHandleReset(name){
                if(this.filedArr.length){
                    this.$Message.warning({content:'请等待当前文件上传,或者刷新页面重新上传',duration: 5})
                }else{
                    this.progressflag = false
                    this.flag = 0 //清空标志位,防止进度条错乱
                    this.progress=0 // 重置进度条
                }
                this.$refs[name].resetFields();
            },
			//获取profile列表
			getProfileData(){
                getProfile()
                    .then(res=>{
                        if(res.data.code == 1){
                        	let profiles = res.data.data;
	                        profiles.forEach(item=>{
	                        	item.id = item.id + ''
                            })
                            this.profileList = profiles;
                        }else {
                            this.$Message.error('获取镜像列表失败！')
                        }
                    })
                    .catch(err=>{
                        this.$Message.error('服务连接失败！')
                    })

            },
			getProfileName(id){ //收集profileName
               let result = this.profileList.find(item=>{
                   return item.id==id
                })
                if(result){
                    this.imageFormData.profileName = result.osName
                }
            },

			handleUpload(file){
                this.progressflag = true
                this.flag = 0 //清空标志位,防止进度条错乱
                this.progress=0 // 重置进度条
                let fileType = ['qcow2','QCOW2','docker','DOCKER']
                // 新加上传过程
                if (file) {
                    if(!file.name.includes('.')){
                        this.$Message.error({content:'请添加文件类型后缀',duration:5})
                        return false
                    }
                    let FileExt = file.name.replace(/.+\./, "");//取得文件的后缀名
                    let newName = file.name.replace('.'+FileExt,'') //取得文件除了后缀之外的名字
                    if(!fileType.includes(FileExt)){   // 添加上传的镜像文件类型验证
                        this.progressflag = false //关闭文件上传进度展示
                        this.$Message.error({content:'请上传qcow2、docker类型的镜像',duration:5, closable: true})
                        return false
                    }
                    if(FileExt == 'qcow2' || FileExt == 'QCOW2'){
                        this.imageFormData.virtualization = 'kvm'
                    }else if(FileExt == 'docker' || FileExt == 'DOCKER'){
                        this.imageFormData.virtualization = 'docker'
                    }
                    let Newfile = new File([file], newName, {
                            type: file.type
                    })
                    if (file.size > 1024 * 1024) {
                        this.imageFileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB'
                    } else {
                        this.imageFileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB'
                    }
                    this.imageFormData.file = Newfile;
                    this.upload(file)
                }
                
                return false;
            },
			upload(file){
                if(file.size<=0){
                    this.$Message.error({
                        content:'无效文件!',
                        duration:3
                    })
                    this.progressflag = false
                    return 
                }
                this.setDisabled = true //禁用选择文件按钮和提交按钮
                this.filedArr = []
                var clientId = this.generateClientId() //id
                var fileName = file.name; 
                var size = file.size
                if(file.size<1024*1024*600){
                    var shardSize = file.size ; //如果上传的文件小于600M直接以当前文件为一个分片
                }else{
                    shardSize = 1024*1024*50 ; //如果上传的文件大于600M就以50M为一个分片
                }
                var chunks = Math.ceil(size/shardSize); //总片数
                for( var i = 0;i<chunks;++i){
                    var start = i*shardSize; //计算每一片的起始位置
                    var end = Math.min(size,start+shardSize)  //计算每一片的结束位置
                    var partFile = file.slice(start,end)
                    this.filedArr.push(partFile)
                };
                //上传分片请求函数
               const partUpload = async(clientId,filedArr,fileName,chunks,chunkId)=>{
                   try {
                        let _this = this
                        let partFile = filedArr[chunkId]
                        var form = new FormData(); 
                        form.append('clientId',clientId); //客户端id
                        form.append('file',partFile); // slice方法 用于切出文件的一部分
                        form.append('fileName',fileName); // 文件名
                        form.append('chunks',chunks); // 总片数
                        form.append('chunkId',chunkId); //当前是第几片
                        const res = await _this.axios({
                            method:'post',
                            url:`${this.baseURL}/resource-manager/upload/part`,
                            data:form,
                            headers:{
                                'Content-type':'multipart/form-data',
                            },
							timeout:0,
                            onUploadProgress: progressEvent => {
                            if (file.size > 1024 * 1024) {
                                this.imageFileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB'
                            } else {
                                this.imageFileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB'
                            }
                                this.fileName = file.name
                                if(file.size<1024*1024*600){
                                var complete = Math.floor(progressEvent.loaded / progressEvent.total * 100)
                                _this.progress = complete
                                }
                                var newTime = +new Date()
                                var DTime = (newTime - this.oldTime)/1000
                                this.oldTime = newTime

                                var aspeed = Number(progressEvent.loaded - _this.loaded)/(1024*1024)
                                _this.loaded = progressEvent.loaded
                                if(aspeed/DTime<1){
                                   _this.speedd = (Math.round(aspeed/DTime*1024*100)/100).toString()+ 'kB/s'
                                }else{
                                    _this.speedd = (Math.round(aspeed/DTime*100)/100).toString()+ 'MB/s'
                                } 
                            },
                        });
                        if(res.data.code==1){
                            chunkId+=1
                            if(chunkId<this.filedArr.length){
                               _this.loaded = 0
                                this.flag+=1
                                var complete = Math.ceil(this.flag/chunks *100)   //当前进度所占总进度的百分比
                                this.progress = complete
                                partUpload(clientId,this.filedArr,fileName,chunks,chunkId)
                            }else{
                                this.flag+=1
                                var complete = Math.ceil(this.flag/chunks *100)   //当前进度所占总进度的百分比
                                this.progress = complete
                                if(this.progress==100){
                                this.setDisabled = false //打开提交和选择文件按钮权限
                               _this.loaded = 0
                                this.speedd = 0//置空速度
                                this.filedArr = []
                                this.$Message.success({
                                    content:'文件上传成功!',
                                    duration:3
                                    
                                })
                                // this.mergeFile(clientId,fileName)
																this.imageFormData.tempId = clientId
                              }
                            }
                        }
                   } catch (error) {
                       console.log(error)
                   } 
                   
                } 
                partUpload(clientId,this.filedArr,fileName,chunks,0)
            },
			//所有文件上传完毕之后的合并接口回调
            mergeFile(clientId, fileName){
                
                var formMerge = new FormData();
                formMerge.append("clientId", clientId);
                formMerge.append("fileName", fileName);
                mergeFiles(formMerge)
                .then(res=>{
                    if(res.data.code==1){
                        this.imageFormData.tempId=res.data.data
                    }
                }
                ).catch(err=>{
                    this.$Message.error('合并文件出错')
                })
            },
			//文件的唯一ID
            generateClientId(){
                var counter = 0;
                var clientId = (+new Date()).toString(32),
                    i = 0;
                for (; i < 5; i++) {
                    clientId += Math.floor(Math.random() * 65535).toString(32);
                }
                return clientId + (counter++).toString(32);
            },
			// 提交镜像
            submitBtn(name){
                this.creatImageHandleSubmit(name)
            },
			creatImageHandleSubmit(name){
                let _this = this
                this.$refs[name].validate((valid) =>{
                    if(valid){
                        let param = {
                            imageName: _this.imageFormData.imageName,
                            minDisk: _this.imageFormData.minDisk + '',
                            minRam: _this.imageFormData.minRam + '',
                            visibility:_this.imageFormData.visibility,
                            virtualization: _this.imageFormData.virtualization,
                            nodeType: _this.imageFormData.nodeType,
                            osType: _this.imageFormData.osType,
                            qga: _this.imageFormData.hasQga + '',
                            cloud: _this.imageFormData.hasCloudInit + '',
                            virtio: _this.imageFormData.hasVirtoDriver + '',
                            htPlug: _this.imageFormData.htPlug + '',
                            description: _this.imageFormData.description,
                            profileId: _this.imageFormData.profileId,
                            profileName:_this.imageFormData.profileName,
                            tempId:_this.imageFormData.tempId,   
                        }
                        for (let key in param) {
                            if (!param[key]) {
                                param[key] = null
                            }
                        }
                        if(!this.progressflag){
                                this.$Message.error('请选择文件上传！')
                            return
                        }
                        // let params = _this.$Qs.stringify(param, { skipNulls: true })
                        _this.addImageBtnLoading = true
                        _this.setDisabled = true
                        _this.axios({
                            method:'post',
                            url:`${_this.updateUrl}`,
                            data:param,
                            headers:{
                            'Content-type':'application/json',
                            },
                        })
                            .then(res=>{
                                if(res.data.code==1){
									// this.getAllImage() // 更新已有镜像列表
									this.$emit('getAllImage')
                                    this.imageFormData.file = null
                                    this.imageModal = false
                                    this.setDisabled = false
                                    this.addImageBtnLoading = false
                                    // this.refreshImage()
									const obj = {
										label:res.data.data.imageName,
										value:res.data.data.id

									}
									// this.changeImage(obj) //创建完直接选中展示
									this.$emit('changeImage',obj)
                                    this.$Notice.info({
                                            title: '镜像消息通知',
                                            desc: '镜像上传完成，更新到云服务器仍需要3到5分钟，请在之后刷新镜像列表查看',
                                            duration: 0
                                        });
                                }
                            })
                            .catch(err=>{
                                _this.$Message.error('服务器连接失败！')
                                _this.addImageBtnLoading = false
                                _this.setDisabled = false
                            })
                    }else {
                        this.$Message.error('请完善信息！');
                    }
                })
            },
			// 关闭创建脚本的modal框后清空校验提示
			watchStatus(status){
				if(!status){
					this.$refs.scriptForm.resetFields()
				}
			}
        },
        mounted(){
           this.queryDictionaries() // 查询字典内容
        }
    }
</script>

<style scoped >
	.dictionaries{
        width: 500px;
        padding: 10px;
        box-sizing: border-box;
        position: absolute;
        top: 50%;
        right: -500px;
        background: var(--card-body-bgcolor);
        border-radius: 10px;
    }

	.pre-Info {
		white-space: pre-wrap;
		background-color: var(--select-bgcolor);
		border: 1px solid #e4e4e4;
		border-radius: 4px;
		color: #333;
		display: block;
		font-size: 13px;
		line-height: 1.42857;
		margin: 5px 0 0;
		padding: 5px;
		word-break: break-all;
		word-wrap: break-word;
		min-height: 35px;
		width: 100%;
		box-sizing: border-box;
		
	}
    .pre-Info code{
        background-color: transparent;
        border-radius: 0;
        color: inherit;
        font-size: inherit;
        padding: 0;
        white-space: pre-wrap;
    }
	.ios-alert{   
        /* position: absolute;
        top: -44px;
        right: -404px; */
        color: orange;
        font-size: 16px;
        cursor: pointer;
    }

	.too{
        position: absolute;
        left: 113px;
        top: -1px;
    }
</style>